#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>

// 错误退出宏
#define ERR_EXIT(name)      \
    do                      \
    {                       \
        perror((name));     \
        exit(EXIT_FAILURE); \
    } while (0)

#define PATH "."
#define FILE_NAME "fifo"
#define DEFAULT_MODE 0666

class Pipe
{
public:
    // 构造函数用于创建管道
    Pipe(const std::string &path, const std::string &name) : _path(path), _name(name)
    {
        _path_name = path + "/" + name;
        // 创建管道文件
        umask(0);
        int n = mkfifo(_path_name.c_str(), DEFAULT_MODE);
        if (n < 0)
        {
            ERR_EXIT("Pipe");
        }
    }
    // 析构函数用于删除管道文件
    ~Pipe()
    {
        int n = unlink(_path_name.c_str());
        if (n < 0)
        {
            ERR_EXIT("unlink");
        }
        std::cout << "~Pipe：unlink success" << std::endl;
    }

private:
    std::string _path = "."; // 不写路径默认当前路径
    std::string _name = "default_fifo";
    std::string _path_name = _path + "/" + _name;
};

class PipeOper
{
public:
    PipeOper(const std::string &path, const std::string &name):_path(path),_name(name),_fd(-1)
    {
         _path_name = _path + "/" + _name;
    }
    int OpenForRead()
    {
        _fd = open(_path_name.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("OpenForRead");
        }
        std::cout << "OpenForRead: open success" << std::endl;
        return _fd;
    }
    int OpenForWrite()
    {
        _fd = open(_path_name.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("OpenForWrite");
        }
        std::cout << "OpenForWrite: open success" << std::endl;
        return _fd;
    }
    void Read()
    {
        char buffer[1024] = {0};
        while (true)
        {
            ssize_t flag = read(_fd, buffer, sizeof(buffer) - 1);
            if (flag > 0)
            {
                buffer[flag] = 0;
                std::cout << "client say #" << buffer << std::endl;
            }
            else if (flag == 0)
            {
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
            }
        }
    }
    void Write()
    {
        std::cout << "请输入消息> " << std::endl;
        // 写入信息
        std::string message;
        // std::cout<<"fd:"<<_fd<<std::endl;
        while (true)
        {
            std::cin >> message;
            if (message == "quit")
            {
                break;
            }
            int flag = write(_fd, message.c_str(), message.size());
        }
    }
    void Close()
    {
        close(_fd);
        std::cout << "close success" << std::endl;
        ;
    }

private:
    int _fd;
    std::string _path;
    std::string _name;
    std::string _path_name;

};